package com.samsung.adapter;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.samsung.item.RestoreItem;
import com.samsung.sbackup.R;

public class RestoreItemsAdapter extends BaseAdapter {

	ArrayList<RestoreItem> dataModel;
	Context ctx;
	int layoutResID;

	public RestoreItemsAdapter(Context ctx, int layoutResId,
			ArrayList<RestoreItem> list) {
		this.ctx = ctx;
		this.layoutResID = layoutResId;
		this.dataModel = list;
	}

	public ArrayList<RestoreItem> getAllItems() {
		ArrayList<RestoreItem> items = new ArrayList<RestoreItem>();
		for (RestoreItem item : dataModel) {
			items.add(item);
		}
		return items;
	}

	public void addItem(RestoreItem item) {
		dataModel.add(item);
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return dataModel.size();
	}

	@Override
	public RestoreItem getItem(int position) {
		return dataModel.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		Holder holder;
		if (convertView == null) {
			convertView = ((Activity) ctx).getLayoutInflater().inflate(
					layoutResID, parent, false);
			holder = new Holder(convertView);
			convertView.setTag(holder);
		} else
			holder = (Holder) convertView.getTag();
		holder.populateFrom(getItem(position));

		return convertView;
	}

	class Holder {
		ImageView iv;
		TextView tv;
		RadioButton radioBtn;
		RestoreItem item;

		public Holder(View v) {
			iv = (ImageView) v.findViewById(R.id.restore_items_iv);
			tv = (TextView) v.findViewById(R.id.restore_items_tv);
			radioBtn = (RadioButton) v
					.findViewById(R.id.restore_items_radioBtn);
			radioBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					item.setChecked(isChecked);
				}
			});
		}

		public void populateFrom(RestoreItem item) {
			this.item = item;
			iv.setImageResource(item.getImgResID());
			tv.setText(item.getName());
			radioBtn.setChecked(item.isChecked());
		}
	}
}
